
from ..database.db import get_db, get_db1
from fastapi import APIRouter, Depends, HTTPException, status
from sqlalchemy.orm import Session
from ..crud.folder_crud import create_folder, delete_folder, get_user_folder_tree, update_folder, \
    get_user_only_folder_tree
from pydantic import BaseModel
from ..utils.jwt_handler import get_username
from ..schemas.base import ResponseModel
from ..crud.user_crud import get_user_by_name
from ..crud.folder_source_crud import create_folder_source, update_folder_source, \
    get_resources_by_folder_id, sort_resources_by_name_prefix, move_resource

folder = APIRouter(prefix="/folder", tags=["文件夹管理"])

from typing import List, Optional, Dict, Any


# class Tree(BaseModel):
#     id: int
#     name: str
#     parent_id: Optional[int] = None
#     children: List["Tree"] = []
#
#
# class TreeResponse(ResponseModel):
#     data: Tree | None = None
# 获取当前用户文件夹树
@folder.get("/tree")
async def read_user_folders(db: Session = Depends(get_db), username: str = Depends(get_username)):
    user = get_user_by_name(db, username)
    if not user:
        raise HTTPException(status_code=404, detail="User not found")

    raw_data = get_user_folder_tree(db, user.id)
    tree_list = raw_data.get(user.id, [])  # 提取当前用户的数据列表

    # 将字典结构转换为 Tree 实例列表
    # trees = [Tree(**tree_dict) for tree_dict in tree_list]

    return {
        "code":200,
        "message":"success",
        "data":tree_list
    }


class FolderCreate(BaseModel):
    name: str
    parent_id: int | None = None
    # user_id: int




# 创建文件夹
@folder.post("/create", status_code=status.HTTP_201_CREATED)
async def create_new_folder(folder_data: FolderCreate, db: Session = Depends(get_db),
                      username: str = Depends(get_username)):

    user_id = get_user_by_name(db,username).id
    folder_name=folder_data.name
    folder_parent_id=folder_data.parent_id
    folder = create_folder(db,folder_name,folder_parent_id,user_id )
    return {
        "code": 200,
        "message": "ok",
        "data": {
            "id": folder.id,
            "name": folder.name,
            "parent_id": folder.parent_id,
            "user_id": folder.user_id
        }
    }

class FolderUpdate(BaseModel):
    name: str

class FolderModel(BaseModel):
    name: str
    parent_id: int


# 更新文件夹
@folder.put("/{folder_id}",response_model=ResponseModel)
async def update_existing_folder(folder_id: int, folder_data: FolderModel, db: Session = Depends(get_db),username: str = Depends(get_username)):
    """
    # 可移动文件夹
    """
    user_id = get_user_by_name(db,username).id
    name=folder_data.name
    folder_parent_id=folder_data.parent_id
    success = update_folder(db, folder_id,name,folder_parent_id,user_id)
    if not success:
        raise HTTPException(status_code=404, detail="Folder not found")
    return ResponseModel(code=200, message="Folder updated successfully",data=success.as_dict())


# 删除文件夹
@folder.delete("/{folder_id}",response_model=ResponseModel)
async def delete_existing_folder(folder_id: int, db: Session = Depends(get_db),username: str = Depends(get_username)):
    success = delete_folder(db, folder_id)
    if not success:
        raise HTTPException(status_code=404, detail="Folder not found")
    return ResponseModel(code=200, message="删除成功")

class FolderSourceMove(BaseModel):
    id: int
    folder_id: int
    resource_type: str
    resource_id: int

class FolderSourceMoveResponse(ResponseModel):
    data: FolderSourceMove

class FolderSourceMoveParm(BaseModel):
    """
    文件夹移动请求体模型
    """
    resource_id: int = ...  # 必填字段
    "要移动的文件夹ID"
    resource_type: str = ...
    new_folder_id: int = ...
    "目标文件夹ID"
@folder.post("/movesource",response_model=FolderSourceMoveResponse)
async def move_folder(
    request: FolderSourceMoveParm,
    db: Session = Depends(get_db),
    username: str = Depends(get_username)
):
    """
        移动文件夹与资源关联信息。

        - **source_id**: 文件夹与资源结合的 ID
        - **new_folder_id**: 要移动到的目标文件夹 ID

        | 资源类型   |
        |------------|
        | textbook   |
        | paper      |
        | voice      |
        | ppt        |
        | image      |
        | video      |

    """
    new_distination = move_resource(db, request.resource_id, request.resource_type, request.new_folder_id)
    return {
        "code": 200,
        "message": "ok",
        "data": new_distination
    }

@folder.get("/treefolder")
async def read_user_folders(db: Session = Depends(get_db), username: str = Depends(get_username)):
    """
    # 仅获得文件夹树
    """
    user = get_user_by_name(db, username)
    if not user:
        raise HTTPException(status_code=404, detail="User not found")

    raw_data = get_user_only_folder_tree(db, user.id)
    tree_list = raw_data.get(user.id, [])  # 提取当前用户的数据列表

    # 将字典结构转换为 Tree 实例列表
    # trees = [Tree(**tree_dict) for tree_dict in tree_list]

    return {
        "code":200,
        "message":"success",
        "data":tree_list
    }

@folder.post("/sources")
async def save_source(folder_id: int=...,db: Session = Depends(get_db),username: str = Depends(get_username)):
    result=get_resources_by_folder_id(db,folder_id)
    return{
        "code":200,
        "message":"success",
        "data":result
    }

@folder.post("/search")
async def search_folder(folder_id:int=...,search_text:str=...,db: Session = Depends(get_db),username: str = Depends(get_username)):
    result=get_resources_by_folder_id(db,folder_id)
    return sort_resources_by_name_prefix(result,search_text)
